package com.aaa.sso.service;

import com.aaa.common.bo.User;
import com.aaa.common.constants.ExceptionConstant;
import com.aaa.common.constants.ReturnCode;
import com.aaa.common.util.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


/**
 * @Author: YuXin
 * @Date : Created in 2020/11/12 17:10
 * @ClassName : UserServiceImpl
 * @Description :
 * @Package_Name : com.aaa.sso.service
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result userLogin(String userName, String password) {
        //收集用户信息
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName, password);
        //获取主体对象
        Subject currentUser = SecurityUtils.getSubject();
        //登录 执行认证的过程
        try {
            currentUser.login(usernamePasswordToken);
            User user = (User) currentUser.getPrincipal();
            //生成token值  String token= UUID.randomUUID().toString();
            String token = userName + System.currentTimeMillis();
            //放入redis     3, TimeUnit.MINUTES  3分钟
            redisTemplate.opsForValue().set(token, user, 2, TimeUnit.DAYS);
            return new Result<>(ReturnCode.SUCCESS.getCode(), ReturnCode.SUCCESS.getMsg(), token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        return new Result<>(ExceptionConstant.ERROR_USERNAME_OR_PASSWORD.getErrorCode(), ExceptionConstant.ERROR_USERNAME_OR_PASSWORD.getErrorMessage(), null);
    }

    @Override
    public boolean checkToken(String token) {
        return redisTemplate.hasKey(token);
    }
}
